const express = require('express');
const router = express.Router();
const db = require('../db/index')

// 获取根据商品id轮播图
router.get('/getShopCarousel', (req, res) => {
    console.log(req.query); // 获取前端传过来的数据get
    const id = req.query.id;
    const sql = 'select * from shopdetailimg where shop_id=?';
    db.query(sql, id, (err, result) => {
        if (err) return res.send({
            status: 301,
            message: err
        })
        res.send({
            status: 200,
            data: result
        })
    })
})

// 获取根据id商品详情
router.get('/getShopInfo', (req, res) => {
    const id = req.query.id;
    const sql = 'select * from hotshop where id=?';
    db.query(sql, id, (err, result) => {
        if (err) return res.send({
            status: 301,
            message: err
        })
        res.send({
            status: 200,
            data: result
        })
    })
})

// 上传文件测试

const multer = require('multer'); // 导入multer模块
const path = require('path')
const { v4: uuidv4 } = require('uuid');
let fielName = '';
function generateRandomUniqueString() {
    return uuidv4().replace(/-/g, ''); // 去除 UUID 中的横杠
}

// 配置Multer存储引擎
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, './static/home/');
    },
    filename: (req, file, cb) => {
        const ext = path.extname(file.originalname);
        fielName = generateRandomUniqueString() + ext
        cb(null, fielName);
    },
});

// 初始化Multer对象并将其与Express应用程序关联起来
const upload = multer({ storage: storage });

router.post('/upload', upload.single('file'), (req, res) => {
    //  文件名称
    // console.log(fielName)
    let host = 'http://127.0.0.1:3006/static/home/' + fielName
    const sql = 'insert into slideimg(img) values(?)'
    db.query(sql, host, (err, result) => {
        if (err) return res.send({
            status: 301,
            message: err
        })
        if (result.affectedRows !== 1) return res.cc('上传banner图失败')
        res.send('文件上传成功!');
    })

});


module.exports = router